<?php

namespace app\api\controller\wanlshop;

use app\common\Codes;
use App\Exceptions\SysExceptions;
use app\index\model\wanlshop\Auth;
use EasyWeChat\Factory;
use think\Controller;
use think\Db;
use think\Exception;
use think\Validate;

class Shopapi extends Controller
{


    public function shopinfo(){
        $data = (new Auth())->where('user_id',input('user_id'))->find();
        return Codes::success('',$data);
    }

    public function add_info(){
        $post = request()->post();
        $post['verify'] = 2;
        $post['name'] = $post['shopname'];
        $rule = [
            'username'  => 'require|length:3,30',
            'password'  => 'require|length:6,30',
            'email'     => 'require|email',
            'mobile'    => 'regex:/^1\d{10}$/',
        ];

        $msg = [
            'username.require' => 'Username can not be empty',
            'username.length'  => 'Username must be 3 to 30 characters',
            'password.require' => 'Password can not be empty',
            'password.length'  => 'Password must be 6 to 30 characters',
            'email'            => 'Email is incorrect',
            'mobile'           => 'Mobile is incorrect',
        ];
        $password = $post['mobile'].'...';
        $data = [
            'username'  => $post['mobile'],
            'password'  => $password,
            'email'     => $post['email'],
            'mobile'    => $post['mobile'],
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (!$result) {
            return Codes::error($validate->getError());
        }

        $resMsg = \app\common\library\Auth::instance()->checkData($data['username'],$data['password'],$data['email'],$data['username']);
        if($resMsg !== true){
            return Codes::error($resMsg);
        }



        $user_id = $post['user_id'];
        Db::startTrans();
        try {
            $entry = (new \app\index\model\wanlshop\Auth())->where(['user_id' => $user_id])->find();
            if($entry){
              $entry ->allowField(true)->save($post);
            }else{
                $post['user_id'] = $user_id;
             (new \app\index\model\wanlshop\Auth()) ->allowField(true)->save($post);
            }

            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            return Codes::error($exception->getMessage());
        }
        return Codes::success('success',[
            'password'=>$password
        ]);
    }


    public function qrcode(){
        $config = [
            'app_id' => 'wxf27de1e7b2c6f136',
            'secret' => 'd811f817176fbbdcbfc7ee0b25fecc8d',

            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];
        $app = Factory::miniProgram($config);
        $response = $app->app_code->get('/pages/user/auth/auth?spread_id='.input('user_id'));
        $filename = '';
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save(ROOT_PATH.'public/qr_code/','qr_code'.input('user_id').'.png');
        }
        if($filename == ''){
            return Codes::error('error生成失败');
        }
        return Codes::success('success',[
            'url'=>$_SERVER['SERVER_NAME'].'/qr_code/'.$filename
        ]);
    }




    public function user_hexiao(){
        $post = request()->post();
        $shopInfo = model('app\api\model\wanlshop\Auth')->where('user_id',$post['user_id'])->find();
        if($shopInfo['state'] != 3){
            return Codes::error('商家类型不正确');
        }
        if(!($post['money'] > 0))
            return Codes::error('请输入金额');
        if(!($post['percent'] > 0))
            return Codes::error('请输入比例');



        $uppers = [];
        $spread_id = model('app\common\model\User')->where('id',$post['b_user_id'])->value('spread_id');
        if($spread_id != 0){
            $spread_u_id = $spread_id;
            while (true){
                $uppers[] = $spread_u_id;
                $spread_u_id = model('app\common\model\User')->where('id',$spread_u_id)->value('spread_id');
                if($spread_u_id == 0){
                    break;
                }
            }
        }

        //商家价格总
        $shop_price = bcmul($post['money'],$post['percent'],2);
        //手续费
        $shop_fee = bcmul($post['money'],0.06,2);

        $user_shop_info = model('app\common\model\User')->where('id',$post['user_id'])->find();
        if($user_shop_info['money'] < bcadd($shop_fee,$shop_price,2)){
            return Codes::error('商家钱包金额不足');

        }

        //消费值
        //让利值

        $userInfo = model('app\common\model\User')->where('id',$post['b_user_id'])->find();

        Db::startTrans();
        //各种值
        try {
            model('app\common\model\ShopPricesOrder')->save([
                'shop_user_id'=>$post['user_id'],
                'user_id'=>$post['b_user_id'],
                'percent'=>$post['percent'],
                'money'=>$post['money']
            ]);
            $gp = bcmul($post['money'],$post['percent'],2)*10;

            model('app\common\model\User')->scorex($gp,$post['b_user_id'],'奖励消费贡献值',0,0,$uppers);
            $rl = bcmul(bcmul($post['money'],$post['percent'],2)*10,0.1,2);
            if($userInfo['spread_id'] != 0){
                model('app\common\model\User')->scorex($rl,$userInfo['spread_id'],'奖励分享贡献值',2,0);
            }
            model('app\common\model\User')->scorex($rl,$post['user_id'],'奖励商家贡献值',1,0);
            //扣除商家消费券
            controller('addons\wanlshop\library\WanlPay\WanlPay')->money(-($shop_price), $post['user_id'], '扣除商家订单让利费', 'pay_shop_fee', time());
            controller('addons\wanlshop\library\WanlPay\WanlPay')->money(-($shop_fee), $post['user_id'], '扣除商家订单手续费', 'pay_shop_rangli', time());
            Db::commit();
            return Codes::success();
        }catch (Exception $exception){
            Db::rollback();
            return Codes::error($exception->getMessage());
        }

    }


    public function moneysLog(){
        $post = request()->post();
        $data = model('app\common\model\ShopPricesOrder')
            ->where('shop_user_id',$post['user_id'])->order('id desc')->paginate();
        return Codes::success('',$data);
    }
}